package com.example.administrator.demo;

/**
 * projectName rxjavademo
 * date 2017/7/21
 * description com.example.administrator.demo
 */

public class JavaMain {

    public static void main(String[] args){
        String s = "01 03 0C 01 90 00 01 00 00 00 37 77 96 6E 74 BC 3A";
        p(hexStringToBytes(s));

    }

    /**
     * 16进制字符串转换为byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase().replace(" ", "");
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    private static void p(byte[] b){
        StringBuffer stringBuffer = new StringBuffer();
        int size = b.length;
        for(int i = 1; i <= size; i++){
            int index = i - 1;
            stringBuffer.append("序号" + i + " : ").append(byteToInt(b[index])).append("\n");
        }
        System.out.println(stringBuffer.toString());
    }

    public static int byteToInt(byte b) {
        //Java 总是把 byte 当做有符处理；我们可以通过将其和 0xFF 进行二进制与得到它的无符值
        return b & 0xFF;
    }
}
